package com.ljx.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.Domain.Setmeal;
import com.ljx.Domain.SetmealDish;
import com.ljx.Dto.SetmealDto;
import com.ljx.Exception.AssociatedException;
import com.ljx.Mapper.SetmealMapper;
import com.ljx.Service.SetmealDishService;
import com.ljx.Service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    SetmealDishService setmealDishService;
    /**
     * 增加套餐
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveSetmeal(SetmealDto setmealDto) {
        //保证setmeal类中的数据
        this.save(setmealDto);
        //获取setmealId
        Long setmealId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //使用stream流，把id保存到setmealDishes
        setmealDishes = setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());
        //保存进数据库
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐
     * @param ids
     */
    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //判断套餐是否在售
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);
        int count = this.count(wrapper);
        if(count>0){
            //在售，不能删除
            throw new AssociatedException("套餐在售，不能删除");
        }
        //未售，可以删除
        //删除----setmeal
        this.removeByIds(ids);
        //删除----setmeal_Dish
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(wrapper1);

    }
}
